package com.reactim.message.config.validation;

import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import org.springframework.util.StringUtils;

/**
 * Redis键前缀验证器
 */
public class RedisKeyPrefixValidator implements ConstraintValidator<ValidRedisKeyPrefix, String> {
    
    private boolean requireColonSuffix;
    private int minLength;
    private int maxLength;
    
    @Override
    public void initialize(ValidRedisKeyPrefix constraintAnnotation) {
        this.requireColonSuffix = constraintAnnotation.requireColonSuffix();
        this.minLength = constraintAnnotation.minLength();
        this.maxLength = constraintAnnotation.maxLength();
    }
    
    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if (!StringUtils.hasText(value)) {
            return true; // 让@NotBlank处理空值
        }
        
        // 检查长度
        if (value.length() < minLength || value.length() > maxLength) {
            context.disableDefaultConstraintViolation();
            context.buildConstraintViolationWithTemplate(
                String.format("Redis键前缀长度必须在%d到%d字符之间，当前长度: %d", minLength, maxLength, value.length())
            ).addConstraintViolation();
            return false;
        }
        
        // 检查是否包含非法字符
        if (value.contains(" ") || value.contains("\t") || value.contains("\n")) {
            context.disableDefaultConstraintViolation();
            context.buildConstraintViolationWithTemplate(
                "Redis键前缀不能包含空格、制表符或换行符"
            ).addConstraintViolation();
            return false;
        }
        
        // 检查是否以冒号结尾
        if (requireColonSuffix && !value.endsWith(":")) {
            context.disableDefaultConstraintViolation();
            context.buildConstraintViolationWithTemplate(
                "Redis键前缀必须以冒号(:)结尾，建议格式: 'reactim:connection:'"
            ).addConstraintViolation();
            return false;
        }
        
        return true;
    }
}